package com.hc.programming.interview;

import java.util.Map;
import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CyclicBarrier;

/**
 * 精灵云二面题：
 * ConcurrentHashMap，一个线程A在往里面put元素，触发了扩容。扩容的同时，另一个线程B也去put，那么线程B会怎么样
 *
 * @author huangchao E-mail:fengquan8866@163.com
 * @version 创建时间：2024/7/25 14:34
 */
public class ConcurrentHashMap扩容时多线程插入 {

    private static Map<String, Integer> map = new ConcurrentHashMap<>();

    private static int count = 1000 * 10000;

    public static void main(String[] args) {
        CyclicBarrier barrier = new CyclicBarrier(2);
        System.out.println(System.currentTimeMillis() + "-开始多线程提交任务");
        for (int i = 0; i < 2; i++) {
            new Thread(() -> {
                try {
                    barrier.await();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } catch (BrokenBarrierException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("子线程开始执行：" + Thread.currentThread().getId());
                Random random = new Random();
                for (int j = 0; j < count; j++) {
                    int n = random.nextInt(count);
                    String key = "key" + n;
                    map.put(key, n);
                }
            }).start();
        }
        System.out.println(System.currentTimeMillis() + "-执行结束");
    }
}
